package question.condtion;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: javase
 * @description: 如果不使用判断标志位
 * @author: lld
 * @create: 2021-06-07 20:52
 **/
public class Demo1 {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{
            for (int i = 1; i < 100; i++) {
                data.print1();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 1; i < 100; i++) {
                data.print2();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 1; i < 100; i++) {
                data.print3();
            }
        },"C").start();
    }
}
class Data{
    private ReentrantLock lock=new ReentrantLock();
    private Condition condition1=lock.newCondition();
    private Condition condition2=lock.newCondition();
    private Condition condition3=lock.newCondition();
    private int n=1;

    public void print1(){
        try {
//            获得锁
            lock.lock();
//        判断等待
            if(n!=1){
                condition1.await();
            }
//           业务
            System.out.println(Thread.currentThread().getName()+": "+1);
            n=2;
//            唤醒
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void print2(){
        try {
//            获得锁
            lock.lock();
//        判断等待
            if(n!=2){
                condition2.await();
            }
//           业务
            System.out.println(Thread.currentThread().getName()+": "+2);
            n=3;
//            唤醒
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void print3(){
        try {
//            获得锁
            lock.lock();
//        判断等待
            if(n!=3){
                condition3.await();
            }
//           业务
            System.out.println(Thread.currentThread().getName()+": "+3);
            n=1;
//            唤醒
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
